package edu.nf.db.util;

import java.beans.BeanInfo;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 行处理器工具类，将一类记录转换为Array,Map,Bean等对象
 *
 * @author zhu
 * @date 2024-05-08
 */
public class RowProcessor {

    /**
     * 将结果集转换为 Array
     * @param rs 结果集对象
     * @return Array结果集对象
     * @throws SQLException SQL异常
     */
    public static Object[] toArray(ResultSet rs) throws SQLException {
        // 通过rs的元数据获取查询的列数并构建Object[]
        Object[] result = new Object[rs.getMetaData().getColumnCount()];
        for (int i = 0; i < result.length; i++){
            result[i] = rs.getObject(i + 1);
        }
        return result;
    }

    /**
     * 根据列名获取某个值
     *
     * @param rs 结果集
     * @param columnName 列名
     * @return 当前列的值
     * @throws SQLException SQL异常
     */
    public static Object toValue(ResultSet rs, String columnName) throws SQLException {
        return rs.getObject(columnName);
    }

    /**
     * 根据列名获取某个值
     *
     * @param rs 结果集
     * @param columnIndex 列的下标
     * @return 当前列的值
     * @throws SQLException SQL异常
     */
    public static Object toValue(ResultSet rs, Integer columnIndex) throws SQLException {
        return rs.getObject(columnIndex);
    }

    /**
     * 将结果集转换为 Map
     *
     * @param rs 结果集
     * @return Map结果集对象
     * @throws SQLException SQL异常
     */
    public static Map<String, Object> toMap(ResultSet rs) throws SQLException {

        Map<String, Object> result = new HashMap<>();
        ResultSetMetaData metaData = rs.getMetaData();

        for (int i = 1; i <= metaData.getColumnCount(); i++){
            result.put(metaData.getColumnLabel(i), rs.getObject(i));
        }

        return result;
    }

    public static <T> T toBean(ResultSet rs, Class<T> beanClass) throws SQLException {
        return BeanProcessor.createBean(rs, beanClass);
    }
}
